<?php

/**
 * Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
 * Copyright (c) 2010 Mr. Ynk: http://www.mrynk.nl
 */

/**
 * @author Michel Ypma: michel@mrynk.nl
 */


require_once('Console/CommandLine.php');

class MytoCLI
{

    private $__parser;
    private $__core;

    public static $outputter;
    /**
     *
     */
    public function __construct ( MytoCore $_core )
    {
        $this->__core = $_core;
        $this->__parser = new Console_CommandLine(array(
            'name' => 'myto',
            'description' => 'Myto - My Transfer Objects generator',
            'version'     => '1.0'
        ));

        $this->registerActions();
        $this->initOptions();
    }

    public function start()
    {
        // startup CLI parser
        try {
            $result = $this->__parser->parse();
        } catch (Exception $exc) {
            $this->__parser->displayError($exc->getMessage());
        }
        //route method
        try {
            call_user_func_array( array( $this->__core, 'execute' ), array( $result->options, $result->args ) );
        } catch (Exception $exc)
        {
            switch( $exc->getCode() )
            {
                case 1024:
                    $this->__parser->displayError($exc->getMessage());
                    break;
                default:
                    $this->__parser->displayUsage( null );
                    break;
            }
        }
    }

    public function initOptions()
    {
        $this->__parser->addOption('gen', array(
            'short_name'  => '-g',
            'long_name'   => '--gen',
            'description' => 'generate all objects',
            'help_name'   => 'FILE',
            'action'      => 'StoreArray'
        ));
        $this->__parser->addOption('class', array(
            'short_name'  => '-c',
            'long_name'   => '--class',
            'description' => 'limit to specific class(es)',
            'help_name'   => 'CLASSNAME',
            'action'      => 'StoreArray'
        ));
    }

    public function registerActions()
    {
        $dirs = new DirectoryIterator( MYTO_LIB . 'cli/actions/' );
        foreach( $dirs as $dir )
        {
            if ( !$dir->isDot() && !$dir->isDir() )
            {
                require_once( MYTO_LIB.'cli/actions/'.$dir->getFilename() );
                $this->__parser->registerAction(
                    strtolower( str_replace( 'Action.php', '', $dir->getFilename() ) ),
                    str_replace( '.php', '', $dir->getFilename() )
                );
            }
        }
    }

    public static function output( $_msg )
    {
        echo $_msg . PHP_EOL;
    }
}

?>